package com.lkd.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkd.common.VMSystem;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.feign.VMService;
import com.lkd.service.VendingMachineService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 补货工单定时任务
 */
@Component
@Slf4j
public class SupplyJob {

    @Autowired
    private VendingMachineService vmService;
    /**
     * 定时扫描售货机任务
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("supplyJobHandler")
    public ReturnT<String> supplyJobHandler(String param) throws Exception{
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        var total = shardingVo.getTotal();//获取总分片数
        var index = shardingVo.getIndex();//获取分片索引
        log.info("分片参数 当前分片索引{}  总分片数{}",index,total);
        XxlJobLogger.log("当前分片索引:"+index+"总分片数"+total);
        QueryWrapper<VendingMachineEntity> vmEntity = new QueryWrapper<>(); //新建查询售货机的条件
        vmEntity.lambda()
                .eq(VendingMachineEntity::getVmStatus, VMSystem.VM_STATUS_RUNNING)//查询正在运行的售货机
                .apply("mod("+total+")="+index); //对id取余
        List<VendingMachineEntity> vmEntityList =vmService.list(vmEntity);
        if (vmEntityList.size()==0) {
            log.error("当前没有售货机运行");
        }
        vmEntityList.forEach(vendingMachine ->{ //遍历售货机列表
            XxlJobLogger.log("当前正在扫描售货机："+vendingMachine.getInnerCode());
            vmService.sendSupplyTask(vendingMachine.getInnerCode()); //对售货机进行补货工单
        });
        return ReturnT.SUCCESS;
    }
}
